package mspbots.data.tl.prod.autotask.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultEntity;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskContractServiceUnitMapper;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskContractServiceUnit;
import mspbots.data.tl.prod.autotask.service.TaskAutotaskContractServiceUnitService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class TaskAutotaskContractServiceUnitServiceImpl extends AbstractBaseServiceImpl<TaskAutotaskContractServiceUnitMapper,TaskAutotaskContractServiceUnit>
        implements TaskAutotaskContractServiceUnitService {

    @Override
    public void sync(ResultEntity content) {
        log.debug("Auto task contractServiceUnit receiver content {}", content);
        JsonNode entity = content.getEntity();
        TaskAutotaskContractServiceUnit data = TaskAutotaskContractServiceUnit.builder()
                .contractServiceUnitId(super.getLongValue(entity.get("id")))
                .vendorCompanyId(super.getLongValue(entity.get("vendorCompanyID")))
                .contractServiceId(super.getIntegerValue(entity.get("contractServiceID")))
                .serviceId(super.getIntegerValue(entity.get("serviceID")))
                .units(super.getIntegerValue(entity.get("units")))
                .contractId(super.getLongValue(entity.get("contractID")))
                .internalCurrencyPrice(super.getDoubleValue(entity.get("internalCurrencyPrice")))
                .startDate(super.getDateTimeValue(entity.get("startDate")))
                .endDate(super.getDateTimeValue(entity.get("endDate")))
                .syncTime(LocalDateTime.now())
                .build();
        data.setTenantCode(content.getTenantId());

        TaskAutotaskContractServiceUnit dbData = super.baseMapper.selectOne(Wrappers.<TaskAutotaskContractServiceUnit>lambdaQuery()
                .eq(TaskAutotaskContractServiceUnit::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskContractServiceUnit::getContractServiceUnitId, data.getContractServiceUnitId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }

    }
}
